package com.cskaoyan.typehandler;



import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {
    @Autowired
    ObjectMapper objectMapper=new ObjectMapper();
    // 预编译的SQL语句提供参数的过程

    /**
     * @param ps PreparedStatement对象
     * @param index ？占位符序号
     * @param parameter 提供的值
     * @throws SQLException
     */
    @Override
    public void setParameter(PreparedStatement ps, int index, Integer[] parameter, JdbcType jdbcType) throws SQLException {
        // Integer[] → String
        String str = null;
        try {
            str = objectMapper.writeValueAsString(parameter);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        ps.setString(index,str);
    }

    // String → Integer[]
    // 从结果集中获取值，转换成set方法能够接受的参数类型
    @Override
    public Integer[] getResult(ResultSet rs, String columnName) throws SQLException {
        String str = rs.getString(columnName);
        Integer[] array = new Integer[0];
        try {
            array = objectMapper.readValue(str, Integer[].class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return array;
    }

    @Override
    public Integer[] getResult(ResultSet rs, int columnIndex) throws SQLException {
        String str = rs.getString(columnIndex);
        Integer[] array = new Integer[0];
        try {
            array = objectMapper.readValue(str, Integer[].class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return array;
    }

    @Override
    public Integer[] getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String str = cs.getString(columnIndex);
        Integer[] array = new Integer[0];
        try {
            array = objectMapper.readValue(str, Integer[].class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return array;
    }
}